package com.shadt.core.initializing;

import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import com.mysql.jdbc.Connection;

/**
 * 数据库初始化
 * @author SongR
 *
 */
public class DBInitializing implements InitializingBean {
	Logger logger = Logger.getLogger(this.getClass());

	public void afterPropertiesSet() throws Exception {
		ResourceBundle bundle = null;
		Connection conn = null;
		Statement statement = null;
		try {
			try {
				bundle = ResourceBundle.getBundle("jdbc");
			} catch (Exception e) {
				logger.error("获取配置文件出错！\n" + e + "\n ending...");
				return;
			}
			Class.forName(bundle.getString("driverClassName")).newInstance();
			logger.info("数据库连接成功！");
			DriverManager.getConnection(bundle.getString("jdbc_url"),bundle.getString("jdbc_username"),bundle.getString("jdbc_password"));
			logger.info("数据库【" + bundle.getString("db_name") + "】已存在!");
		} catch (Exception e) {
			try {
				logger.error("数据库不存在请无视此错误！\n" + e+ "\n ending...\n 准备创建数据库...");
				conn = (Connection) DriverManager.getConnection("jdbc:mysql://"+ bundle.getString("db_host") + "/mysql",bundle.getString("jdbc_username"),bundle.getString("jdbc_password"));
				statement = conn.createStatement();
				String creatDbsql = "CREATE DATABASE  `"+ bundle.getString("db_name")	+ "` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;";
				statement.executeUpdate(creatDbsql);
				logger.info("数据库【" + bundle.getString("db_name")+ "】创建成功!");
			} catch (Exception e2) {
				logger.error("创建数据库出错！\n" + e2 + "\nending...");
				return;
			}
		} finally {
			logger.info("数据库初始化结束！");
		}
	}

}
